//
//  SettingViewController.m
//  Custom_Weibo
//
//  Created by LEO on 12/19/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "SettingViewController.h"
#import "EmojiPanelView.h"
@interface SettingViewController ()<UIImagePickerControllerDelegate,
UINavigationControllerDelegate, TapImageViewDelegate, EmojiViewDelegate>

@end

@implementation SettingViewController {
    UITextView *_textView;          //  For inputing words.
    UIView *_editBar;               //  For editing tool bar.
    UIProgressView *_progressView;  //  For showing the uploading progress.
    
    TapImageView *_thumbImageView;  //  For showing the detail image.
    EmojiPanelView *_emojiPanel;    //  For emoji panel using.
}

- (void)viewWillAppear:(BOOL)animated {
    //  Make the bar opaque.
    self.navigationController.navigationBar.translucent = NO;
    
    [_textView becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //  Monitor when keyboard is showed.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self editNavigationItems];
    [self editView];
    [self editThumbImageView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - EDIT_NAVIGATION_ITEMS
- (void)editNavigationItems {
    //  1)Close button for backward.
    ThemeButton *closeButton = [ThemeButton buttonWithType:UIButtonTypeCustom];
    CGRect closeFrame = CGRectMake(0, 0, kNavigationItemSize, kNavigationItemSize);
    closeButton.frame = closeFrame;
    closeButton.defalutImageName = @"button_icon_close";
    [closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:closeButton];
    self.navigationItem.leftBarButtonItem = closeItem;
    
    //  2)Send button for posting weibo.
    ThemeButton *sendButton = [ThemeButton buttonWithType:UIButtonTypeCustom];
    CGRect sendFrame = CGRectMake(0, 0, kNavigationItemSize, kNavigationItemSize);
    sendButton.frame = sendFrame;
    sendButton.defalutImageName = @"button_icon_ok";
    [sendButton addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *sendItem = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    self.navigationItem.rightBarButtonItem = sendItem;
}

#pragma mark EDIT_MAIN_VIEW
- (void)editView {
    //  1)Text input view.

    
    CGRect textViewFrame = CGRectMake(0, 0, kScreenWidth, 2 * kNavigationBarHeight);
    _textView = [[UITextView alloc] initWithFrame:textViewFrame];
    _textView.backgroundColor = [UIColor lightGrayColor];
    _textView.layer.borderColor = [UIColor blackColor].CGColor;
    _textView.layer.borderWidth = 3;
    _textView.layer.cornerRadius = 10;
    [self.view addSubview:_textView];
    
    //  2)Edit the tool bar.
    CGRect toolbarFrame = CGRectMake(0, kScreenHeight, kScreenWidth, kNavigationBarHeight);
    _editBar = [[UIView alloc] initWithFrame:toolbarFrame];
    _editBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_editBar];
    
    //  3)Edit the button on the tool bar.
    NSArray *images = @[
                        @"compose_toolbar_1",
                        @"compose_toolbar_4",
                        @"compose_toolbar_3",
                        @"compose_toolbar_6",
                        @"compose_toolbar_5"];
    
    for (NSInteger i = 0; i < images.count; i++) {
        NSString *imageName = images[i];
        
        ThemeButton *button = [ThemeButton buttonWithType:UIButtonTypeCustom];
        CGRect buttonFrame = CGRectMake(20 + i * kBottomButtonWidth, 20,
                                        kNavigationItemSize, kNavigationItemSize);
        button.frame = buttonFrame;
        button.defalutImageName = imageName;
        button.tag = kEditBarbuttonTag + i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_editBar addSubview:button];
    }
    
    //  4)Edit the emoji panel view.
    _emojiPanel = [[EmojiPanelView alloc] initWithFrame:CGRectZero];
    _emojiPanel.top = kScreenHeight - kNavigationBarHeight;
    [_emojiPanel setEmojiViewDelegate:self];
    [self.view addSubview:_emojiPanel];
}

#pragma mark EDIT_EMOJI_PANEL
- (void)showEmojiPanel {
    [UIView animateWithDuration:0.3 animations:^{
        _emojiPanel.bottom = kScreenHeight - kNavigationBarHeight;
        _editBar.bottom = _emojiPanel.top;
    }];
}

- (void)hideEmojiPanel {
    [UIView animateWithDuration:0.3 animations:^{
        _emojiPanel.top = kScreenHeight - kNavigationBarHeight;
    }];
}

- (void)emojiDidSelect:(NSString *)emojiName {
    NSString *text = _textView.text;
    NSString *newText = [NSString stringWithFormat:@"%@%@", text, emojiName];
    _textView.text = newText;
}

#pragma mark EDIT_TUHMBIMAGE_VIEW
- (void)editThumbImageView {
    CGRect thumbFrame = CGRectMake(10, 0, kThumbImageWidth, kThumbImageHeight);
    _thumbImageView = [[TapImageView alloc] initWithFrame:thumbFrame];
    _thumbImageView.top = _textView.bottom + 10;
    _thumbImageView.backgroundColor = [UIColor lightGrayColor];
    _thumbImageView.hidden = YES;
    _thumbImageView.delegate = self;
    [self.view addSubview:_thumbImageView];
}

#pragma mark - EDIT_BAR_ACTION
- (void)sendAction {
    NSString *text = _textView.text;
    NSString *error = nil;
    
    if (text.length == 0) {
        error = @"No content";
    } else if (text.length > 140) {
        error = @"Your have input more than 140 words";
    }
    
    if (error != nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning"
                                                                       message:error
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"YES"
                                                              style:UIAlertActionStyleDefault
                                                            handler:NULL];
        [alert addAction:alertAction];
        
        [self presentViewController:alert animated:YES completion:NULL];
    }
    
    NSURLSessionDataTask *task = [NetworkService sendWeibo:text
                                                     image:_thumbImageView.image
                                                     block:^(id result, NSURLResponse *response, NSError *error) {
        [self closeAction];
    }];
    
    //  If the progress view is not being added, add one to show uploading progress.
    if (_progressView == nil) {
        CGRect progressFrame = CGRectMake(0, 0, kScreenWidth, 20);
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = progressFrame;
        _progressView.progress = 0.0;
        [self.view addSubview:_progressView];
    }
    [_progressView setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
                                              animated:YES];
}

- (void)closeAction {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if ([window.rootViewController isKindOfClass:[MMDrawerController class]]) {
        
        MMDrawerController *mmDrawer = (MMDrawerController *)window.rootViewController;
        [mmDrawer closeDrawerAnimated:YES completion:NULL];
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)buttonAction:(ThemeButton *)button {
    if (button.tag == kEditBarbuttonTag) {
        [self selectPhotos];
    }else if (button.tag == kEditBarbuttonTag + 3) {
        //  If the keyboard isn't show, then the emoji panel doesn't show either.
        if (_textView.isFirstResponder) {
            [_textView resignFirstResponder];
            [self showEmojiPanel];
        }else {
            [self hideEmojiPanel];
            [_textView becomeFirstResponder];
        }
    }
}

#pragma mark - PHOTO_SELECTED
- (void)selectPhotos {
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"Choice"
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"Album"
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * _Nonnull action) {
        [self pickPhoto:NO];
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Camera"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * _Nonnull action) {
        [self pickPhoto:YES];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel"
                                                     style:UIAlertActionStyleCancel
                                                   handler:nil];
    
    [actionSheet addAction:album];
    [actionSheet addAction:camera];
    [actionSheet addAction:cancel];
    
    [self presentViewController:actionSheet animated:YES completion:nil];
}

#pragma mark PHOTO_PICKER
- (void)pickPhoto:(BOOL)isCamera {
    UIImagePickerControllerSourceType sourceType;
    
    //  Make sure whether it turns into album, or open camera.
    if (isCamera) {
        sourceType = UIImagePickerControllerSourceTypeCamera;
        
        //  When you try to use camera, make sure if it is available.
        BOOL isCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:
                                  UIImagePickerControllerCameraDeviceRear];
        if (!isCameraAvailable) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning"
                                                                message:@"Rear camera is unavailable"
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:nil];
            [alertView show];
            return;
        }
    }else {
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIIMAGEPICKER_DELEGATE
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _thumbImageView.image = image;
    _thumbImageView.hidden = NO;
}

#pragma mark - TAPIMAGEVIEW_DELEGATE
- (void)imageZoomOut:(TapImageView *)imageView {
    [_textView becomeFirstResponder];
}

- (void)imageZoomIn:(TapImageView *)imageView {
    [_textView resignFirstResponder];
}

#pragma mark - KEYBOARD_SHOW
- (void)keyboardShow:(NSNotification *)notification {
    //  Get the keyboard frame.
    NSValue *bonusValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    //  Get keyboard height and set the tool bar's height.
    CGRect frame = [bonusValue CGRectValue];
    _editBar.bottom = frame.origin.y - kNavigationBarHeight;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
